<template>
    <!-- 排渣口列表 -->
	<div id="lineAndPoly">
		<a-tree
             v-model:checkedKeys="checkedKeys"
			:show-line="showLine"
			:show-icon="showIcon"
			:defaultExpandAll="true"
			:tree-data="treeList"
			checkable
			@select="onSelect"
            @check="onCheck"
		>
			<!-- <template #icon>
				<FileSyncOutlined />
			</template> -->
			<template #title="{ dataRef }">
				<template v-if="dataRef.key === '0-0-0-1'">
					<div>multiple line title</div>
					<div>multiple line title</div>
				</template>
				<template v-else>{{ dataRef.title }}</template>
			</template>
			<template #switcherIcon="{ dataRef, defaultIcon }">
                
				<FileSyncOutlined v-if="dataRef.key == '0-01'" />
				<component :is="defaultIcon" v-else />
			</template>
		</a-tree>
	</div>
</template>
<script setup>
let baseURL = import.meta.env.MODE == "development" ? 'http://sittest.rybsj.cn': window.location.origin
import { ref, reactive, defineProps, watch, onMounted, watchEffect,nextTick } from 'vue';
import {customborder,customborder3} from '../views/mapBorder'
import {banline1, banline2} from '../views/mapLines'
import surveillance_camera from '../assets/surveillance-camera.gif'
import online from '../assets/online.png'
import offline from '../assets/offline.png'
import errorStatus from '../assets/errorStatus.png'
import dayjs from 'dayjs';
import {
	saveItem,
	getItems,
	getItemById,
	updateItem,
	deleteItem,
} from '../dbFence2';
import { api_get } from '../untils/common.js'
import ndList from '../static/localData/ndList.json'
import iw_close1d3gif from '../assets/iw_close1d3.gif'
const showLine = ref(true);
const showIcon = ref(true);

const props = defineProps({
	overlays: Object, // 地图覆盖物（需要在父级）（当前组件有对它赋值操作）
	updateOverlays: Function,
	updateList: String,
	updateAmenuTopList: Function,
	catMap: Object,
});


// watch(() => props.overlays,async (newValue) => {
//     props.overlays.value = newValue
// });
watch(()=>props.updateList,(newValue)=>{
	updateTreeList()
})

//   如果没有固定的假数据， saveItem 它， 因为用在ant数，form的表单数据为默认值

const formDataByDBList = ref(null);
const treeList = ref([]);


const expandedKeys = ref([7788, 8888]);
const checkedKeys = ref([]);



watch(checkedKeys, (e,a) => {
    console.log(props.overlays,'xx');
	console.log('checkedKeys', checkedKeys,a);
});

import getData from '../static/localData/getData.json'

const updateTreeList = async ()=> {
    const response = await api_get('/webgis/applet/getData.action', { cors: true });
    console.log(response,'response');
    let list = getData.data;  //test
    if (__prd__) list = response.data.data//api
    function addKeysToNestedObjects(items) {
        return items.map((item,index) => {  
            let position = {longitude:ndList[index]['LONGITUDE'].toFixed(6)*1 ,latitude:ndList[index]['LATITUDE'].toFixed(6)*1 }
            const newItem = {...item, key: item.id, title: item.text, ...position};  
            if (Array.isArray(item.children)) {  
                newItem.children = addKeysToNestedObjects(item.children);
            }
            return newItem;  
        });  
    }  
    list = addKeysToNestedObjects(list);
    list.forEach(parentVal => {  
    // 检查parentVal是否有children属性  
        if (Array.isArray(parentVal.children)) {  
            // 遍历children数组  
            parentVal.children.forEach(childVal => {  
                let position = [childVal.longitude.toFixed(6)*1 , childVal.latitude.toFixed(6)*1 ];  
                addMarker(position, childVal);  
            });  
        }  
        // 注意：这里没有为parentVal（即顶级元素）调用addMarker  
    });
    treeList.value = list
    
    // formDataByDBList.value.push(...await getItems('govLine'))
    
    console.log(treeList.value, 'treeList');
    
}

let closeImg

onMounted(async () => {
	formDataByDBList.value = await getItems();
	
    // 测试演示使用
    // addPolygon(customborder,'', 7788);
    // addPolygon(customborder3,'', 7789);
    // addPolyline(banline1,'', 8888);
    // addPolyline(banline2,'', 8889);
    
    nextTick( ()=>{
        setTimeout(() => {
            updateTreeList()
            props.updateAmenuTopList()
        }, 500);
    })

    let marker
        
    let div = document.createElement('div')
        div.innerHTML = `<div id="InfoWindowContainer" style="display:none; background: #15285bad;border: 1px solid; padding: 10px; border-radius: 9px; font-size: 13px;">
                    
                </div>
                <iframe src="" id="InfoWinVideo" allow="fullscreen" width="635px" height="560px" frameborder="0"></iframe>`

    closeImg = document.createElement('img');
    closeImg.className = `close mapclose`;
    closeImg.src = iw_close1d3gif;
    closeImg.addEventListener('click', () => {
        // 在这里处理关闭事件
        console.log(`Close button clicked`);
        window.aMapInfoWindow.hide()
    });
    div.append(closeImg)

    
    marker = new AMap.InfoWindow({
        isCustom: true,  //使用自定义窗体
        position: [106.653651, 38.099586],
        offset: new AMap.Pixel(16, -45),
        content: div
    });
    if (window.aMapInfoWindow) {
        window.aMapInfoWindow.setContent(div)
    } else {
        window.aMapInfoWindow = marker
        props.catMap.add(marker);
        marker.hide()
    }

});
// 获取getItem 数据后对数据处理成ant树数据格式


const onSelect = (selectedKeys, info) => {
	console.log('selected', selectedKeys, info);
  let paddings = [160,200,400,400].map(val=>val*=.9)
    props.catMap.setFitView(props.overlays[info.node.key],false,paddings)
};

// 根据选中节点显示或隐藏覆盖物
// 当前添加覆盖物的列表中如果它们的key和复选框数据key一致, 进行显示隐藏

// 同样，checked选中时显示，取消时隐藏覆盖物
const onCheck = (checkedKeys, checked) => {
    let reslOS = [],
    checkedNode = checked.node

  checkedKeys.forEach(key => {
    if (props.overlays[key]) {
        checked ? props.overlays[key].show() : props.overlays[key].show();
        reslOS.push(props.overlays[key])
    }
  });

  Object.keys(props.overlays).forEach(key => {
    if (!checkedKeys.includes(key)) {
        if (props.overlays[key].getExtData().zhakou) {
            props.overlays[key].hide();
        }
    }
  });
    


    // let checkedStatus = checked.node.checked
    // if (!checkedStatus) props.overlays[checkedEventKey].show();

  let paddings = [160,200,400,400].map(val=>val*=.9)
  if (checked.checked && checkedKeys.length>1) {
    if (checkedNode['children'].length>1)
    // 会报错 ???!!!
        props.catMap.setFitView(reslOS,false,paddings)
  }

  
  return
  if (!props.overlays[checkedEventKey]) {
    if (checkedEventKey!='0-0' && checkedEventKey!='0-1') {
        
        let checkedNodeData = formDataByDBList.value.filter(item=>item.id==checkedEventKey)

        checkedNodeData = checkedNodeData?checkedNodeData[0]:[]

        let lnglats = checkedNodeData.points.split(';')
        let path = lnglats.map(lnglat=>{
            return lnglat.split(',')
        })
        
        if (checkedNodeData.areaType == 'govArea' || checkedNodeData.areaType == 'polygon') {
            addPolygon(path,checkedNodeData['name'], checkedEventKey);

        }
        if (checkedNodeData.areaType == 'govLine') {
            addPolyline(path,checkedNodeData['name'], checkedEventKey);

        }
        setTimeout(() => {
            props.catMap.setFitView(props.overlays[checkedEventKey],false,paddings);
        }, 1);
    } else {
        if (checked.checked) {

            checked.node.children.forEach(node=>{
                let checkedNodeData = formDataByDBList.value.filter(item=>item.id==node.key)
                
                checkedNodeData = checkedNodeData?checkedNodeData[0]:[]
                console.log(checkedNodeData.name,'checkedNodeData');
    
                let lnglats = checkedNodeData.points.split(';')
                let path = lnglats.map(lnglat=>{
                    return lnglat.split(',')
                })
                
                if (checkedNodeData.areaType == 'govArea') {
                    addPolygon(path,checkedNodeData['name'], checkedNodeData.id);
    
                }
                if (checkedNodeData.areaType == 'govLine') {
                    addPolyline(path,checkedNodeData['name'], checkedNodeData.id);
    
                }
                // setTimeout(() => {
                //     props.catMap.setFitView(props.overlays[checkedNodeData.id],false,paddings);
                // }, 1);
            })
        }
    }
  }
};


let zIndexAddNum = 1

// 地图显示marker点)可点击该点视频查看, 同时列表显示固废列表


function addMarker(position, val) {
    let title = val.title,
        key = val.key,
        carRunStatus = online
    if (val.iconCls == '0') 
        carRunStatus = offline

    if (!props.overlays[key]) {
        let content = `
            <div><img class="markerlnglat" src="${carRunStatus}"><span class="marker kou">${title}</span></div>
        `
        props.overlays[key] = new AMap.Marker({
            // icon: surveillance_camera,
            position: position,
            offset: new AMap.Pixel(-13, -30),
            content:content,
            extData: {
                zhakou: true
            }
        });
        props.overlays[key].on('click', async () => {
            const response = await api_get('/webgis/applet/getRtsp.action?channelId=' + val.describe, { cors: true });
            let rtspUrl = response.data.data.rtsp
            // div.innerHTML = `<iframe src="${baseURL}/webgis/iccDH/icc.html?adaptive_page=1&sing_page=1&rtspUrl=${rtspUrl}" allow="fullscreen" width="635px" height="560px" frameborder="0"></iframe>`
            
            
            document.querySelector('#InfoWindowContainer').style.display = 'none'
            document.querySelector('#InfoWinVideo').style.display = 'block'
            window.aMapInfoWindow.setPosition(position)
            document.querySelector('#InfoWinVideo').src = `${baseURL}/webgis/iccDH/icc.html?adaptive_page=1&sing_page=1&rtspUrl=${rtspUrl}`
            props.catMap.setFitView([props.overlays[key],window.aMapInfoWindow],true,[650, 60, 60, 60])
            window.aMapInfoWindow.show()
        })
        props.catMap.add(props.overlays[key]);
        props.overlays[key].hide()
    }
  
//   let paddings = [160,200,600,600].map(val=>val*=.9)
    // props.catMap.setFitView(Object.values(markerKous),false,paddings)
}

function addPolyline(path, where = '', key) {
    var polyline = new AMap.Polyline({
        path: path,
        isOutline: true,
        outlineColor: 'transparent',
        borderWeight: 3,
        strokeColor: "#e52b1d",
        strokeOpacity: 1,
        strokeWeight: 3,
        // 折线样式还支持 'dashed'
        strokeStyle: "solid",
        // strokeStyle是dashed时有效
        strokeDasharray: [5, 5],
        lineJoin: 'round',
        lineCap: 'round',
    })
    var text = new AMap.Text({
        text: where + "禁行路线", //标记显示的文本内容
        anchor: "center", //设置文本标记锚点位置
        draggable: true, //是否可拖拽
        cursor: "pointer", //指定鼠标悬停时的鼠标样式。
        angle: -2, //点标记的旋转角度
        style: {
            //设置文本样式，Object 同 css 样式表
            "padding": "0.15rem .35rem",
            "margin-bottom": "1rem",
            "border-radius": "0.25rem",
            "background-color": "rgb(21 40 91 / 58%)",
            "border-width": "0px",
            "text-align": "center",
            "font-size": "12px",
        },


        position: [path[0][0], path[0][1]], //点标记在地图上显示的位置
    });
    polyline.on('mouseover', () => {

        text.setMap(props.catMap);
    })
    polyline.on('mouseout', () => {
        props.catMap.remove(text)
    })
    props.catMap.add(polyline);
    props.overlays[key] = polyline
    DBAddItem(key, key, path, 'govLine')
    // props.catMap.setFitView();
}

function addPolygon(path, where='', key) {
    // 使用map和forEach来遍历并修改每个坐标  
    path = path.map(coordinates => {  
        return coordinates.map(coordinate => parseFloat((coordinate*1).toFixed(6)));  
    });  
    let layData = {
        path: path,
        fillColor: 'darkred',
        strokeOpacity: 1,
        fillOpacity: 0.5,
        strokeColor: 'blue',
        strokeWeight: 1,
        strokeStyle: 'dashed',
        strokeDasharray: [5, 5],
        zIndex: 50 + zIndexAddNum,
    }
    if (key == 7789) {
        layData = {strokeColor: '#FF33FF',
        strokeWeight: 2,
        fillOpacity: .3,
        fillColor: '#1791fc',
        zIndex:49}
        layData.path = path
    }

    let polygon
    if (!props.overlays[key]) {
        polygon = new AMap.Polygon(layData);
    } else {
        polygon = props.overlays[key]
    }
    
    zIndexAddNum++
    //   text.setMap(catMap); //将文本标记设置到地图上
    let bounds = polygon.getBounds()
    let lng = bounds['northEast']?bounds['northEast'].lng:bounds['northeast']?bounds['northeast'].lng:''
    let lat = bounds['northEast']?bounds['northEast'].lat:bounds['northeast']?bounds['northeast'].lat:''
    var text = new AMap.Text({
        text: where + "禁行区域", //标记显示的文本内容
        anchor: "center", //设置文本标记锚点位置
        draggable: true, //是否可拖拽
        cursor: "pointer", //指定鼠标悬停时的鼠标样式。
        angle: -2, //点标记的旋转角度
        style: {
            //设置文本样式，Object 同 css 样式表
            "padding": "0.15rem .35rem",
            "margin-bottom": "1rem",
            "border-radius": "0.25rem",
            "background-color": "rgb(21 40 91 / 58%)",
            "border-width": "0px",
            "text-align": "center",
            "font-size": "12px",
        },
        
        position: [lng, lat], //点标记在地图上显示的位置
    });
    
    if (key != 7789) {

        polygon.on('mouseover', () => {
            text.setMap(props.catMap);
            polygon.setOptions({
                fillOpacity: 0.7,
                fillColor: 'blue'
            })
        })
        polygon.on('mouseout', () => {
            props.catMap.remove(text)
            polygon.setOptions({
                fillOpacity: 0.5,
                fillColor: 'red'

            })
        })
    }
    if (!props.overlays[key]) {
        props.overlays[key] = polygon
        props.catMap.add(polygon);
        let areaName = key
        if (key == 7789) {
            areaName ='宁东镇'
        }
        DBAddItem(areaName, key, path, 'govArea')
    } else {
        polygon.show()
    }

}


async function DBAddItem(name, key, path, areaType){
    if (Array.isArray(path)) {
        path = path.join(';')
    }
    let FormData = {
        name,
        key,
        id: key,
        userName: '管理员',
        byShare: true,
        byDependency: true,
        bymanor: true,
        byTime: true,
        limitSpeed: true,
        originGpsCoord: true,
        areaType,
        maxSpeed: "90.0",
        startDate: '',
        endDate: '',
        epidemicRisk: '低风险',
        delay: 10,
        glv: 20,
        date: [
            dayjs().startOf('month'),
            dayjs()
        ],
        adname: '',
        txnr: '',
        points: path,
        alarmTypes1s: '',
        alarmTypes2s: '',
        alarmType: '',
        type: '',
        checkedList1: ['进区域报警给驾驶员', '进区域报警给平台'],
        checkedList2: ['进区域报警给驾驶员', '进区域报警给平台'],
        approver: '',
        dateTime: null,
        description: '',
    }
    
    var formInitData = reactive(FormData);
    let rs = await getItemById(areaType, key)
    if (!rs) {
        await saveItem(areaType, formInitData)
    }
}
</script>
<style>
/* .ant-tree-switcher-line-icon {
    display: none;
} */
.ant-tree-switcher-noop span svg {
    display: none;
}
.ant-tree-switcher-noop  {
    display: flex;
    align-items: center;
}
.ant-tree-switcher-noop span {
    width: 20px;
    height: 20px;
    background: url(../assets/treeicon.png);
    background-size: cover;
    background-size: 16px 16px;
    background-position: bottom;
    background-repeat: no-repeat;
}
.ant-tree-switcher-noop span::after {
    content:'1',
}
#lineAndPoly .ant-tree-checkbox:not(.ant-tree-checkbox-disabled) .ant-tree-checkbox-inner {
	background-color: transparent;
	opacity: 0.65;
}

.ant-tree .ant-tree-checkbox:not(.ant-tree-checkbox-disabled) .ant-tree-checkbox-inner {
	border-color: #d9d9d98a;
}

.mapclose {
  position: absolute;
  width: 14px;
  height: 14px;
  cursor: pointer;
  z-index: 99;
  right: -14px;
  top: -8px;
}

.marker.kou {
  right: -58px;
}

.markerText.kou {
  left: 0;
}

.markerText {
  position: absolute;
  top: 30px;
  color: #fff;
  padding: 4px 10px;
  box-shadow: 1px 1px 1px rgba(10, 10, 10, .2);
  white-space: nowrap;
  font-size: 12px;
  font-family: "";
  background-color: #25a5f7;
  border-radius: 3px;
}

.ant-tabs .ant-tabs-tabpane {
    overflow: auto;
}
</style>
